const axios = require('axios');

async function getAccessToken() {
  const appId = process.env.WECHAT_APP_ID;
  const secret = process.env.WECHAT_SECRET;
  const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${appId}&corpsecret=${secret}`;
  const response = await axios.get(url);
  return response.data.access_token;
}

async function sendToGroups(groups, contentType, mediaId, textContent) {
  const accessToken = await getAccessToken();
  const url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${accessToken}`;

  let messageData = {};
  switch (contentType) {
    case 'text':
      messageData = {
        touser: '@all',
        msgtype: 'text',
        agentid: process.env.AGENT_ID,
        text: {
          content: textContent
        },
        safe: 0
      };
      break;
    case 'image':
      messageData = {
        touser: '@all',
        msgtype: 'image',
        agentid: process.env.AGENT_ID,
        image: {
          media_id: mediaId
        },
        safe: 0
      };
      break;
    case 'video':
      messageData = {
        touser: '@all',
        msgtype: 'video',
        agentid: process.env.AGENT_ID,
        video: {
          media_id: mediaId
        },
        safe: 0
      };
      break;
    case 'link':
      messageData = {
        touser: '@all',
        msgtype: 'news',
        agentid: process.env.AGENT_ID,
        news: {
          articles: [
            {
              title: 'Link Title',
              description: 'Description of link',
              url: mediaId,
              picurl: 'http://example.com/pic.png' // Optional picture URL
            }
          ]
        },
        safe: 0
      };
      break;
    default:
      throw new Error('Unsupported content type');
  }

  await axios.post(url, messageData);
}

module.exports = { sendToGroups };